import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { Chat } from '@/app/im-system/chat/layout'

interface ChatState {
	// 聊天室列表
	chatList: Chat[]
	// 当前选中的聊天室
	activeChat: Chat | null
	pinnedChats: Set<number>

	// Actions
	setChatList: (chats: Chat[]) => void
	addChat: (chat: Chat) => void
	setActiveChat: (chat: Chat | null) => void
	updateChatStatus: (userId: number, status: 'online' | 'offline') => void
	togglePinChat: (chatId: number) => void
}

export const useChatStore = create<ChatState>()(
	persist(
		(set) => ({
			chatList: [],
			activeChat: null,
			pinnedChats: new Set<number>(),

			setChatList: (chats) => set({ chatList: chats }),

			addChat: (chat) =>
				set((state) => ({
					chatList: [...state.chatList, chat],
				})),

			setActiveChat: (chat) => set({ activeChat: chat }),

			updateChatStatus: (userId, status) =>
				set((state) => ({
					chatList: state.chatList.map((chat) => {
						if (chat.contact.id === userId) {
							return {
								...chat,
								contact: {
									...chat.contact,
									status,
								},
							}
						}
						return chat
					}),
					activeChat:
						state.activeChat?.contact.id === userId
							? {
									...state.activeChat,
									contact: {
										...state.activeChat.contact,
										status,
									},
							  }
							: state.activeChat,
				})),

			togglePinChat: (chatId) =>
				set((state) => {
					const newPinnedChats = new Set(state.pinnedChats)
					if (newPinnedChats.has(chatId)) {
						newPinnedChats.delete(chatId)
					} else {
						newPinnedChats.add(chatId)
					}
					return { pinnedChats: newPinnedChats }
				}),
		}),
		{
			name: 'chat-storage',
			partialize: (state) => ({
				chatList: state.chatList,
				activeChat: state.activeChat,
				pinnedChats: state.pinnedChats,
			}),
		}
	)
)
